#!/usr/bin/env python
# encoding: utf-8
"""
topic.py

Created by 姚 远 on 2009-07-09.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp \
	import template
	
class reply(db.Model):
	when = db.DateTimeProperty(auto_now_add=True)
	who=db.StringProperty()
	cnts=db.TextProperty()
	gd=db.IntegerProperty()
	bd=db.IntegerProperty()
	tpicid=db.IntegerProperty()
	
	
class tpic(db.Model):
	ttl=db.StringProperty()
	when = db.DateTimeProperty(auto_now_add=True)
	who=db.StringProperty()
	cnts=db.TextProperty()
	gd=db.IntegerProperty()
	bd=db.IntegerProperty()


class MainHandler(webapp.RequestHandler):
	def get(self):
		n = self.request.get('id')
		tpics = db.GqlQuery('SELECT * FROM topic')
		replys = db.GqlQuery('SELECT * FROM reply '
		'ORDER BY when DESC')
		values = {
			'n':int(n),
			'tpics':tpics,
			'replys':replys
		}
		self.response.out.write(template.render('topic.html', values))

	def post(self):
		n = self.request.get('id')
		rply = reply(who=self.request.get('who'),cnts=self.request.get('cnts'),tpicid=int(n))
		rply.put()
		self.redirect('/topic.html?id=' + n)

########


class MyHandler(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if user:
      greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" %
                  (user.nickname(), users.create_logout_url("/")))
    else:
      greeting = ("<a href=\"%s\">Sign in or register</a>." %
                  users.create_login_url("/"))

    self.response.out.write("<html><body>%s</body></html>" % greeting)
######
def main():
	  forum = webapp.WSGIApplication([('/topic\.html', MainHandler)],
	                                       debug=True)
	  wsgiref.handlers.CGIHandler().run(forum)

if __name__ == '__main__':
	main()